package loveqq.r2dbc;

import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Mono;

import java.util.Optional;

public class HelloWorld {
    public static void main(String[] args) {
        //url：r2dbc:mysql://账号:密码@IP:端口/数据库
        ConnectionFactory factory = ConnectionFactories.get("r2dbc:mysql://root:root@127.0.0.1:3306/course_db");

        // ConnectionFactory factory = MySqlConnectionFactory.from(MySqlConnectionConfiguration.builder()
        //         .host("127.0.0.1")
        //         .port(3306)
        //         .user("root")
        //         .password("root")
        //         .database("course_db")
        //         .build()
        // );

        // 查询
        Mono.from(factory.create())
                .doOnEach(signal -> Optional.ofNullable(signal.get()).ifPresent(Connection::close))
                .flatMapMany(conn -> conn
                        .createStatement("SELECT * FROM `user` WHERE id > ?")
                        .bind(0, 10)
                        .execute()
                )
                .flatMap(result -> result.map((row, rowMetadata) -> row.get("name", String.class)))
                .doOnNext(name -> System.out.println("name = " + name))
                .blockLast();
        //      .subscribe();    // 如果使用非阻塞，得保证数据库查询结果之前，管道还一直维持
        // while (true) {
        // }

        User user = new User();
        user.setId(100L);
        user.setName("Test");
        user.setAge(25);
        // 新增
        Mono.from(factory.create())
                .doOnEach(signal -> Optional.ofNullable(signal.get()).ifPresent(Connection::close))
                .flatMapMany(conn -> conn
                        .createStatement("INSERT INTO `user`(id,name,age) VALUES (?,?,?)")
                        .bind(0, user.getId())
                        .bind(1, user.getName())
                        .bind(2, user.getAge())
                        .execute()
                )
                .flatMap(result -> result.map((row, rowMetadata) -> row.get("name", String.class)))
                .doOnNext(name -> System.out.println("name = " + name))
                .blockLast();
    }
}
